#!/usr/bin/env python2.2

import re

START=r'''

\documentclass[landscape,letterpaper,twocolumn]{report} 
\usepackage{graphicx,pstcol,epsfig} 

\setlength{\parindent}{0pt} 
\setlength{\columnseprule}{1pt} 
\setlength{\columnsep}{0.5in} % default=10pt 
\setlength{\oddsidemargin}{-0.5in} % default=0in 
\setlength{\evensidemargin}{0in} %default=1in 
\setlength{\textwidth}{10.5in} % default=9in 
\setlength{\textheight}{7.0in} % default=5.15in
\setlength{\headheight}{0in}
\setlength{\topmargin}{0in}
\setlength{\headsep}{0in}
\pagestyle{myheadings} 

\begin{document} 

\DeclareFixedFont{\cursive}{T1}{ppl}{m}{sc}{29.9pt} 
\DeclareFixedFont{\tinycursive}{T1}{ppl}{m}{sc}{20.0pt} 
\DeclareFixedFont{\tinyfixed}{T1}{pcr}{m}{sc}{10.0pt} 
\DeclareFixedFont{\eventtitle}{OT1}{phv}{b}{b}{10pt} 
\DeclareFixedFont{\eventdate}{T1}{phv}{it}{it}{10pt} 
\DeclareFixedFont{\eventbody}{T1}{ptm}{n}{n}{8pt} 

\newcommand{\ActivistNetwork}{\cursive Activist Network} 

\newcommand{\Title}{ 
\begin{pspicture}(0,0)(10,4.0) 
\psset{linestyle=solid} 
\put(5,0.8){\ActivistNetwork} 
\put(5,0){\tinycursive event listings: June, 2004} 
\put(5,-0.5){\tinyfixed http://www.activist.ca} 
\scalebox{0.5}{\put(4,-1.5){\epsfig{file=static/ActivistNetworkLogo.eps}}} 
\end{pspicture} 
} 

\newcommand{\Event}[3] 
{ 
\parbox{\linewidth} 
{ 
\eventtitle #1 \\ 
\eventdate #2 \vspace{0.25em} 

\eventbody #3 
\\ 
\rule{2cm}{0.5pt} 
\vspace{1pt} 
} 
} 

\thispagestyle{empty} % no page numbering 
\rput{0}(2,3){\Title} 

'''

END=r'''
\end{document}
'''

EVENT=r'''\Event{%(title)s}{%(date)s}{%(description)s\\\\%(location)s}

'''


START_RE = re.compile('<p>Showing.*listings in total.</p>')
LISTING_START = re.compile('<p class="(feature)|(listing)">')
LISTING_END = re.compile('</p>')

DATE_RE = re.compile( '<span class="date">(.*)</span>', re.M )
TITLE_RE = re.compile( '<span class="title"><a href=".*">(.*?)</a></span>', re.M )
DESCRIPTION_RE = re.compile( '<br>(.*)<br>(.*)', re.M|re.S )
LOCATION_RE = None

DATA = open('june-events.html','r').readlines()

def clean(s):
    rtn = ''
    skip = False
    for x in s:
        if x is '$':
            rtn = rtn + '\${}'
        elif x is '<':
            skip = True
        elif x is '>':
            skip = False;
        else:
            if not skip:
                rtn = rtn + x
    return rtn

def entityclean(o):
    rtn = ''
    for line in o.split('\n'):
        for word in line.split():
            if word == '&amp;':
                rtn = rtn + '\&{} '
            elif word.find('&#8217;') != -1:
                rtn = rtn + word[:word.find('&#8217;')] + "'" + word[word.find('&#8217;')+7:] + ' '
            else:
                rtn = rtn + word + ' '
        rtn = rtn + '\n'
    return rtn

state = 'start'
listings = []
current = None
for line in DATA:
    if state == 'start':
        if START_RE.search(line):
            print "found start:",line
            state = 'listing'
    elif state == 'listing':
        if LISTING_START.search(line):
            if current:
                listings.append(current)
            current = ''
            state = 'collect'
    elif state == 'collect':
        if LISTING_END.search(line):
            state = 'listing'
        else:
            current = current + line

print "found",len(listings),"listings"

output = START
for listing in listings:
    date = clean(DATE_RE.search(listing).group(1))
    match = TITLE_RE.search(listing)
    title = match.group(1)
    match = DESCRIPTION_RE.search(listing[match.end():])
    if not match:
        print "SKIPPED:",listing
        continue
    description = clean(match.group(1))
    location = clean(match.group(2))

    print date[-len(title):],'vs',title
    if date[-len(title):] == title:
        date = date[:-len(title)]
        print "!",date

    if date.find('From') != -1:
        print "WOO",date[:date.find('From')],"!",date
        date = date[:date.find('From')] + ': ' + date[date.rfind('200')+4:]
        print "   :",date

    if date.find('Deadline') != -1:
        date = date[date.find('Deadline'):]

    output = output + EVENT % {
    'title': title.strip(),
    'date': date.strip(),
    'description': description.strip(),
    'location': location.strip() }

output = output + END
open( 'print.tex', 'w' ).write(entityclean(output))
